using System.Collections.ObjectModel;
using Microsoft.TeamFoundation.VersionControl.Client;

namespace Empanada
{
    class EmpanadaWorkspace
    {
        private readonly Workspace _workspace;
        private readonly ObservableCollection<EmpanadaPendingChange> _changes;

        public EmpanadaWorkspace(Workspace workspace, ObservableCollection<EmpanadaPendingChange> changes)
        {
            _workspace = workspace;
            _changes = changes;

            Reset();
        }

        public Workspace Workspace
        {
            get { return _workspace; }
        }

        public void Reset()
        {
            RefreshChanges();
            Subscribe();
        }

        private void RefreshChanges()
        {
            _changes.Clear();
            foreach (var c in _workspace.GetPendingChanges())
            {
                _changes.Add(ConvertPendingChange(c));
            }
        }

        private void Subscribe()
        {
            var versionControlServer = _workspace.VersionControlServer;
            versionControlServer.NewPendingChange += NewPendingChange;
            versionControlServer.UndonePendingChange += UndonePendingChange;
            versionControlServer.CommitCheckin += CheckinCommitted;
        }

        private void CheckinCommitted(object sender, CommitCheckinEventArgs e)
        {
            if (e.Workspace != _workspace) return;
            foreach (var pendingChange in e.Changes)
            {
                var change = ConvertPendingChange(pendingChange);
                _changes.Remove(change);
            }
        }

        private void UndonePendingChange(object sender, PendingChangeEventArgs e)
        {
            if (e.Workspace != _workspace) return;
            var change = ConvertPendingChange(e.PendingChange);
            _changes.Remove(change);
        }

        private void NewPendingChange(object sender, PendingChangeEventArgs e)
        {
            if (e.Workspace != _workspace) return;
            _changes.Add(ConvertPendingChange(e.PendingChange));
        }

        private EmpanadaPendingChange ConvertPendingChange(PendingChange change)
        {
            return new EmpanadaPendingChange
                       {
                           Path = change.LocalOrServerItem,
                           ChangeTypeName = change.ChangeTypeName, 
                           FileName = change.FileName, 
                           Folder = change.LocalOrServerFolder
                       };
        }


        public void Pause()
        {
            var versionControlServer = _workspace.VersionControlServer;
            versionControlServer.NewPendingChange -= NewPendingChange;
            versionControlServer.UndonePendingChange -= UndonePendingChange;
            versionControlServer.CommitCheckin -= CheckinCommitted;
        }
    }
}